<!--
  @author:  long
  @date:    2024/5/30
  @file:    xx
  @require:
-->
<template>
  <div class="workItemInfo">
    <el-dialog
      v-model="visible"
      :show-close="false"
      width="95vw"
      :close-on-click-modal="false"
      custom-class="workItemInfoDialog"
      @close="handleWorkingDialogClose"
    >
      <el-row>
        <el-col :span="17" class="app-container">
          <div class="flex items-center pl-5px py-3">
            <img
              class="mr-5px"
              :src="requirementTypeIcon[workItemForm.workItemType]"
              alt=""
            />
            <span>{{ workItemForm.id }}</span>
          </div>
          <div
            class="info-title"
            @click="handleInputNameShow"
            v-if="!inputNameShow"
          >
            <div class="info-name">
              {{ workItemForm.title }}
            </div>
          </div>
          <div v-if="inputNameShow">
            <el-input
              ref="inputNameRef"
              v-model="workItemForm.title"
              input-style=" font-size: 1.875rem; height: 45px;"
              @blur="handleFormBlur('title')"
            />
          </div>
          <div class="px-10px pt-10px">
            <el-form
              :model="workItemForm"
              label-position="top"
              ref="workItemInfoRef"
            >
              <el-row :gutter="30">
                <el-col :span="6">
                  <el-form-item label="负责人">
                    <!--                    <div-->
                    <!--                      class="showHideClass"-->
                    <!--                      v-if="!showHideObj.directorId"-->
                    <!--                      @click="handleFormFocus('directorId', 'directorIdRef')"-->
                    <!--                    >-->
                    <!--                      {{-->
                    <!--                        workItemForm.directorId != ''-->
                    <!--                          ? workItemForm.director-->
                    <!--                          : '未设置'-->
                    <!--                      }}-->
                    <!--                      <el-icon class="formIcon ml-2" size="18" color="#cccccc">-->
                    <!--                        <EditPen />-->
                    <!--                      </el-icon>-->
                    <!--                    </div>-->
                    <el-select
                      v-model="workItemForm.directorId"
                      placeholder="负责人"
                      @focus="userInputFocus"
                      class="w-full"
                      ref="directorIdRef"
                    >
                      <el-option
                        v-for="(item, index) in selectOptionObj['directorId']"
                        :key="index"
                        :label="item.label"
                        :value="item.uuid"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="状态">
                    <!--                    <div-->
                    <!--                      class="showHideClass"-->
                    <!--                      v-if="!showHideObj.status"-->
                    <!--                      @click="handleFormFocus('status', 'statusRef')"-->
                    <!--                    >-->
                    <!--                      <dict-tag-->
                    <!--                        v-if="workItemForm.status != ''"-->
                    <!--                        :options="project_backlog_status"-->
                    <!--                        :value="workItemForm.status"-->
                    <!--                      />-->
                    <!--                      <span v-else>未设置</span>-->

                    <!--                      <el-icon class="formIcon ml-2" size="18" color="#cccccc">-->
                    <!--                        <EditPen />-->
                    <!--                      </el-icon>-->
                    <!--                    </div>-->
                    <el-select
                      v-model="workItemForm.status"
                      ref="statusRef"
                      clearable
                      placeholder="状态"
                      @change="handleFormBlur('status')"
                    >
                      <el-option
                        v-for="(dict, index) in project_backlog_status"
                        :label="dict.label"
                        :value="dict.value"
                        :key="index"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="开始时间">
                    <!--                    <div-->
                    <!--                      class="showHideClass"-->
                    <!--                      v-if="!showHideObj.startDate"-->
                    <!--                      @click="handleFormFocus('startDate', 'startDateRef')"-->
                    <!--                    >-->
                    <!--                      {{-->
                    <!--                        workItemForm.startDate != '' &&-->
                    <!--                        workItemForm.startDate != null-->
                    <!--                          ? workItemForm.startDate-->
                    <!--                          : '&#45;&#45;'-->
                    <!--                      }}-->
                    <!--                      <el-icon class="formIcon ml-2" size="18" color="#cccccc">-->
                    <!--                        <EditPen />-->
                    <!--                      </el-icon>-->
                    <!--                    </div>-->
                    <el-date-picker
                      v-model="workItemForm.startDate"
                      type="date"
                      ref="startDateRef"
                      placeholder="开始时间"
                      format="YYYY-MM-DD"
                      @change="handleFormBlur('startDate')"
                      value-format="YYYY-MM-DD"
                      :disabled-date="startDisabledDate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="截止时间">
                    <!--                    <div-->
                    <!--                      class="showHideClass"-->
                    <!--                      v-if="!showHideObj.endDate"-->
                    <!--                      @click="handleFormFocus('endDate', 'endDateRef')"-->
                    <!--                    >-->
                    <!--                      {{-->
                    <!--                        workItemForm.endDate != '' &&-->
                    <!--                        workItemForm.endDate != null-->
                    <!--                          ? workItemForm.endDate-->
                    <!--                          : '&#45;&#45;'-->
                    <!--                      }}-->
                    <!--                      <el-icon class="formIcon ml-2" size="18" color="#cccccc">-->
                    <!--                        <EditPen />-->
                    <!--                      </el-icon>-->
                    <!--                    </div>-->
                    <el-date-picker
                      v-model="workItemForm.endDate"
                      type="date"
                      ref="endDateRef"
                      placeholder="结束时间"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      @change="handleFormBlur('endDate')"
                      :disabled-date="endDisabledDate"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="px-5">
            <el-tabs
              v-model="activeName"
              class="demo-tabs"
              @tab-change="handleTabClick"
            >
              <el-tab-pane label="基本信息" name="basicInfo">
                <div class="flex items-center justify-between">
                  <div>描述</div>
                  <el-icon
                    class="cursor-pointer"
                    v-if="!showHideObj.description"
                    size="20"
                    color="#9f9f9f"
                    @click="handleFormFocus('description', 'descriptionRef')"
                  >
                    <EditPen />
                  </el-icon>
                </div>
                <div
                  v-html="workItemForm.description"
                  v-if="!showHideObj.description"
                ></div>
                <div v-if="showHideObj.description">
                  <editor
                    class="w-full"
                    ref="descriptionRef"
                    v-model="workItemForm.description"
                    :min-height="180"
                  />
                  <div class="mt-2 text-right w-full">
                    <el-button link @click="handleFormBlur('description')"
                      >取消
                    </el-button>
                    <el-button
                      type="primary"
                      class="w80px"
                      @click="handleFormBlur('description')"
                    >
                      确定
                    </el-button>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="操作记录" name="handleLog">
                <OperationLog :tableParam="followUpListParams"></OperationLog>
              </el-tab-pane>
              <el-tab-pane label="附件" name="fileList">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :before-upload="beforeAvatarUpload"
                  :http-request="requestFile"
                  accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt,
              .pptx,.gif, .jpg, .jpeg, .png"
                  :limit="10"
                  :show-file-list="false"
                >
                  <el-button type="primary" style="font-size: 14px">
                    <el-icon>
                      <UploadFilled />
                    </el-icon>
                    添加附件
                  </el-button>
                  <template #tip>
                    <div class="el-upload__tip float-right pl-5px">
                      支持格式.rar .zip .doc .docx .pdf ，单个文件不能超过200MB
                    </div>
                  </template>
                </el-upload>
                <div class="text-14px mt-10px" style="width: 100%">
                  <div
                    v-for="(item, index) in formData.fileList"
                    :key="item.fileName"
                  >
                    <el-link :href="item.url" :underline="false" type="primary"
                      >{{ item.origFileName }}
                    </el-link>
                    <el-button text plain @click="delFileName(index)"
                      >删除
                    </el-button>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col
          :span="7"
          class="h85vh px-10"
          style="background-color: #fafafacc; border-top-right-radius: 10px"
        >
          <div class="w-full pt-6 pb-4 text-right relative">
            <div
              class="flex items-center cursor-pointer absolute"
              v-show="!hoursFormShow"
              @click="hoursFormShow = true"
            >
              <el-icon size="18" color="#999">
                <Back />
              </el-icon>
              <span class="pl-3" style="color: #999">返回</span>
            </div>
            <div>
              <el-tooltip content="关闭" placement="top">
                <!--              <el-button text>-->
                <el-icon
                  size="20"
                  color="#999"
                  cursor-pointer
                  @click="handleClose"
                >
                  <Close />
                </el-icon>
                <!--              </el-button>-->
              </el-tooltip>
            </div>
          </div>
          <!--       基础信息     -->
          <div class="overflow-auto h70vh pr-5" v-show="hoursFormShow">
            <el-form :model="workItemForm" label-width="auto">
              <el-collapse v-model="collapseActiveNames">
                <el-collapse-item title="属性" name="1">
                  <el-form-item label="优先级">
                    <el-select
                      v-model="workItemForm.priority"
                      filterable
                      placeholder="请选择"
                      style="width: 100%"
                      clearable
                      @change="handleFormBlur('priority')"
                    >
                      <el-option
                        v-for="(dict, index) in project_backlog_priority"
                        :label="dict.label"
                        :value="dict.value"
                        :key="index"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="风险">
                    <el-select
                      v-model="workItemForm.risk"
                      filterable
                      placeholder="请选择"
                      clearable
                      style="width: 100%"
                      @change="handleFormBlur('risk')"
                    >
                      <template #prefix v-if="workItemForm.risk != ''">
                        <div
                          :class="[
                            'w8px',
                            'h8px',
                            'rounded-full',
                            'riskColor' + workItemForm.risk
                          ]"
                        ></div>
                      </template>
                      <el-option
                        v-for="(dict, index) in project_risk_level"
                        :label="dict.label"
                        :value="dict.value"
                        :key="index"
                      >
                        <div class="flex items-center">
                          <div
                            :class="[
                              'w8px',
                              'h8px',
                              'rounded-full',
                              'mr-5px',
                              'riskColor' + dict.value
                            ]"
                          ></div>
                          {{ dict.label }}
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="需求类型">
                    <el-select
                      v-model="workItemForm.requirementType"
                      filterable
                      placeholder="请选择"
                      style="width: 100%"
                      clearable
                      @change="handleFormBlur('requirementType')"
                    >
                      <el-option
                        v-for="(dict, index) in project_backlog_type"
                        :label="dict.label"
                        :value="dict.value"
                        :key="index"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="需求来源">
                    <el-select
                      v-model="workItemForm.source"
                      filterable
                      placeholder="请选择"
                      style="width: 100%"
                      clearable
                      @change="handleFormBlur('source')"
                    >
                      <el-option
                        v-for="(dict, index) in project_backlog_source"
                        :label="dict.label"
                        :value="dict.value"
                        :key="index"
                      />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
                <el-collapse-item title="工时" name="2">
                  <el-form-item label="预估工时">
                    <el-input
                      v-model="workItemForm.estimatedWorkHour"
                      placeholder="预计工时"
                      :min="0"
                      type="number"
                      class="w-full"
                      @blur="handleFormBlur('estimatedWorkHour')"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="登记工时">
                    <div class="flex items-center justify-between w-full">
                      <el-input
                        v-model="workItemForm.workHour"
                        class="text-center w-full"
                        disabled
                      >
                        <template #append>
                          <el-button @click="handleShowHoursList">
                            <el-icon>
                              <Document />
                            </el-icon>
                          </el-button>
                        </template>
                      </el-input>
                      <el-button @click="handleSetWorkingHours">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="剩余工时">
                    <el-input
                      type="number"
                      :min="0"
                      v-model="workItemForm.surplusWorkHour"
                      placeholder="剩余工时"
                      class="w-full"
                      @blur="handleFormBlur('surplusWorkHour')"
                    ></el-input>
                  </el-form-item>
                </el-collapse-item>
                <el-collapse-item title="基础信息" name="3">
                  <el-form-item label="项目">
                    <img class="mr-5px" :src="scrumFill" alt="" />
                    {{ projectInfo.name }}
                  </el-form-item>
                  <el-form-item label="创建人">
                    {{ workItemForm.createName }}
                  </el-form-item>
                  <el-form-item label="创建时间">
                    {{ workItemForm.createTime }}
                  </el-form-item>
                  <el-form-item label="更新人">
                    {{ workItemForm.updateName }}
                  </el-form-item>
                  <el-form-item label="更新时间">
                    {{ workItemForm.updateTime }}
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
          <!--      工时列表      -->
          <div class="overflow-auto h70vh pr-5" v-show="!hoursFormShow">
            <div style="border-top: 1px solid #dcdfe6" class="py-10px">
              <div>工时记录</div>
              <el-divider></el-divider>
              <div v-for="(item, index) in hoursDataList" :key="index">
                <div class="px-5">
                  <div class="flex justify-between pt-5px pb-5px">
                    <div class="text-xl">{{ item.workHour }}&nbsp;h</div>
                    <div class="flex items-center">
                      <span class="pr-1 text-xl">{{ item.createBy }}</span>

                      <el-dropdown>
                        <el-button text size="small">
                          <div
                            class="flex items-center justify-center rotate-90 cursor-pointer"
                          >
                            <el-icon>
                              <More />
                            </el-icon>
                          </div>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item
                              @click="handleUpdateHoursInfo(item)"
                            >
                              <div class="flex items-center">
                                <el-icon>
                                  <EditPen />
                                </el-icon>
                                <span class="pl-2">修改</span>
                              </div>
                            </el-dropdown-item>
                            <el-dropdown-item @click="handleDelHours(item)">
                              <div class="flex items-center">
                                <el-icon>
                                  <Delete />
                                </el-icon>
                                <span class="pl-2">删除</span>
                              </div>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                  <div class="flex justify-between py-3px">
                    <div class="text-current flex items-center">
                      <el-icon color="#67C23A" size="18">
                        <SuccessFilled />
                      </el-icon>
                      <span class="pl-1">通过</span>
                    </div>
                    <div class="text-gray-400 text-xl">
                      {{ item.createTime.substring(0, 10) }}
                    </div>
                  </div>
                </div>
                <el-divider></el-divider>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <!--   登记工时弹窗   -->
    <el-dialog
      v-model="workingHoursDialog"
      title="登记工时"
      width="50vw"
      :close-on-click-modal="false"
      :before-close="handleWorkingHoursDialogClose"
    >
      <div class="h60vh px-5 overflow-y-auto overflow-x-hidden">
        <el-form
          label-position="top"
          label-width="auto"
          :rules="rules"
          ref="workingHoursFormRef"
          :model="workingHoursForm"
        >
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="事项类型" prop="typeName">
                <el-input v-model="workingHoursForm.typeName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事项" prop="itemName">
                <el-input
                  v-model="workingHoursForm.itemName"
                  disabled
                ></el-input>
                <!--                <el-select-->
                <!--                  v-model="workingHoursForm.itemName"-->
                <!--                  placeholder="请选择事项"-->
                <!--                  class="w-full"-->
                <!--                >-->
                <!--                  <el-option-->
                <!--                    v-for="item in options"-->
                <!--                    :key="item.value"-->
                <!--                    :label="item.label"-->
                <!--                    :value="item.value"-->
                <!--                  />-->
                <!--                </el-select>-->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预计工时">
                <div class="text-6xl flex items-end">
                  <span>{{ workingHoursForm.estimatedWorkHour }}</span>
                  <div class="text-xl">h</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记工时">
                <div class="text-6xl flex items-end">
                  <span>{{ workItemForm.workHour }}</span>
                  <div class="text-xl">h</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作进度">
                <el-progress
                  type="circle"
                  :percentage="workingHoursForm.percentage"
                  :width="50"
                  :stroke-width="6"
                >
                  <template #default="{}">
                    <span class="text-lg"
                      >{{ workingHoursForm.percentage }}%</span
                    >
                  </template>
                </el-progress>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作时长" prop="workHour">
                <el-input
                  type="number"
                  v-model="workingHoursForm.workHour"
                  :min="0"
                  @blur="workingHoursFormChange('workHour')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="剩余工时">
                <el-input
                  type="number"
                  v-model="workingHoursForm.surplusWorkHour"
                  :min="0"
                  @blur="workingHoursFormChange('surplusWorkHour')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作日期" prop="workTime">
                <el-date-picker
                  v-model="workingHoursForm.workTime"
                  type="date"
                  placeholder="工作日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作类别">
                <el-select
                  v-model="workingHoursForm.workType"
                  filterable
                  placeholder="任务类别"
                  style="width: 100%"
                  clearable
                >
                  <template #prefix v-if="workingHoursForm.workType != ''">
                    <div
                      :class="[
                        'taskTypeIcon',
                        'taskTypeColor' + workingHoursForm.workType
                      ]"
                    ></div>
                  </template>
                  <el-option
                    v-for="(dict, index) in project_task_type"
                    :label="dict.label"
                    :value="dict.value"
                    :key="index"
                  >
                    <div class="flex items-center">
                      <div
                        :class="[
                          'taskTypeIcon',
                          'mr-5px',
                          'taskTypeColor' + dict.value
                        ]"
                      ></div>
                      {{ dict.label }}
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工作说明">
                <editor
                  class="w-full"
                  v-model="workingHoursForm.description"
                  :min-height="180"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button text @click="handleWorkingHoursDialogClose">取 消</el-button>
        <el-button
          type="primary"
          style="width: 80px"
          @click="handleWorkingHoursConfirm"
          >确 定
        </el-button>
      </template>
    </el-dialog>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="handleFormBlur('directorId')"
    ></SelectDialog>
  </div>
</template>

<script setup name="WorkItemInfo">
import {
  delWorkHour,
  getBacklogInfo,
  getWorkHourList,
  savebacklogInfo,
  saveWorkHours,
  updateBacklogProperty
} from '@/api/researchManage/backlog'

//需求类型图标
import epicSquareFill from '@/assets/icons/svg/epicSquareFill.svg'
import featureSquareFill from '@/assets/icons/svg/featureSquareFill.svg'
import userStorySquareFill from '@/assets/icons/svg/userStorySquareFill.svg'
import scrumFill from '@/assets/icons/svg/scrumFill.svg'
import { getCurrentInstance } from 'vue'
import useUserStore from '@/store/modules/user'
import useResearchProjectStore from '@/store/modules/researchProject'
import { ElMessageBox } from 'element-plus'
import OperationLog from '@/businessComponents/OperationLog'
import useCommonStore from '@/store/modules/common'
import { getTreeNodeByParam } from '@/utils/commo'
import { delFile, uploadFile } from '@/api/salesManage/contractManage'

const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const { project_backlog_status } = proxy.useDict('project_backlog_status')

const requirementTypeIcon = ref({
  epic: epicSquareFill,
  feature: featureSquareFill,
  userStory: userStorySquareFill
})
// 工作项类型
const requirementType = ref('epic')
const visible = ref(false) //弹窗打开
const inputNameRef = ref(null)
const directorIdRef = ref(null)
const statusRef = ref(null)
const startDateRef = ref(null)
const endDateRef = ref(null)
const collapseActiveNames = ref(['1', '2', '3'])
const projectInfo = ref({})
// 字典
const {
  project_backlog_priority, //优先级
  project_risk_level, //风险等级
  project_backlog_source, //来源
  project_backlog_type, //类型
  project_task_type
} = proxy.useDict(
  'project_backlog_priority',
  'project_risk_level',
  'project_backlog_source',
  'project_backlog_type',
  'project_task_type'
)

// 表单
const workItemForm = ref({
  title: '',
  directorId: '',
  status: '',
  startDate: '',
  endDate: '',
  description: '',
  risk: '', //风险等级
  requirementType: '', //需求类型
  source: '', //需求来源
  priority: '', //优先级
  estimatedWorkHour: 0, //预计工时
  surplusWorkHour: 0, //剩余工时
  workHour: 0 //登记工时
})
// 标题显示
const inputNameShow = ref(false)
const dialogParam = ref({}) //人员弹窗配置
const selectOptionObj = ref({}) //人员选择下拉
//tabs 选中
const activeName = ref('basicInfo')
const tableData = ref([])
const workingHoursDialog = ref(false) //登记工时弹窗
const workingHoursFormRef = ref(null)
const workingHoursForm = ref({
  workHour: '', //工作时长
  surplusWorkHour: '', //剩余工时
  typeName: '工作项', //事项类型
  itemName: '', //事项名称
  workTime: '', //工作日期
  workType: '', //工作类别
  description: '', //工作说明
  estimatedWorkHour: 0, //预计工时
  percentage: 0 //进度
}) //登记工时表单
const hoursFormShow = ref(true) //表单显示与隐藏
const hoursDataList = ref([]) //工时列表
const followUpListParams = ref({})
// 附件对象
const formData = ref({
  fileList: [] //附件
})
const rules = ref({
  typeName: [{ required: true, message: '请选择事项类型', trigger: 'change' }],
  itemId: [{ required: true, message: '请选择事项', trigger: 'change' }],
  workHour: [{ required: true, message: '请输入工作时长', trigger: 'blur' }],
  workTime: [
    { required: true, message: '请输入工作日期', trigger: 'change,blur' }
  ]
})
const researchProjectStore = useResearchProjectStore()

watch(
  () => researchProjectStore.projectInfo,
  (newVal, oldVal) => {
    console.info('newVal', newVal)
    projectInfo.value = JSON.parse(JSON.stringify(newVal))
  }
)

//  开始
const startDisabledDate = date => {
  if (workItemForm.value.endDate !== '' && workItemForm.value.endDate != null) {
    //结束
    let endDate = new Date(workItemForm.value.endDate).getTime()
    return date >= endDate
  } else {
    return false
  }
}

// 截止
const endDisabledDate = date => {
  if (
    workItemForm.value.startDate !== '' &&
    workItemForm.value.startDate != null
  ) {
    //开始时间
    let startDate = new Date(workItemForm.value.startDate).getTime()

    return date <= startDate
  } else {
    return false
  }
}

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType =
    [
      '.rar',
      '.zip',
      '.doc',
      '.docx',
      '.pdf',
      '.jpg',
      '.png',
      '.gif',
      '.jpeg',
      '.xls',
      '.xlsx'
    ].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      '上传文件只能是.rar、.zip、.doc、.docx、.pdf、.jpg、.png、.gif、.jpeg、.xls、.xlsx格式!'
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}

// 上传附件
function requestFile(params) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)

      formData.value.fileList.push(res.data)
      let params = JSON.parse(JSON.stringify(workItemForm.value))
      params.fileList = formData.value.fileList
      if (selectOptionObj.value['directorId']) {
        params.directorId = selectOptionObj.value['directorId'][0].id
      }

      savebacklogInfo(params).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess('保存成功')
        }
      })
    }
  })
}

// 删除附件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const res = await delFile(formData.value.fileList[index].fileName)
      if (res.code === 200) {
        formData.value.fileList.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
        let params = JSON.parse(JSON.stringify(workItemForm.value))
        params.fileList = formData.value.fileList
        console.info(
          'selectOptionObj.value.directorId',
          selectOptionObj.value.directorId
        )
        if (selectOptionObj.value['directorId']) {
          params.directorId = selectOptionObj.value['directorId'][0].id
        }
        savebacklogInfo(params).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess('保存成功')
          }
        })
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

// 弹窗关闭
const handleWorkingDialogClose = () => {
  visible.value = false
  //触发父级queryList
  proxy.$emit('queryList')
}

//tab切换
const handleTabClick = val => {
  console.info('val', val)
  if (val == 'handleLog') {
    handleGetOperaList()
  }
}

//操作日志
const handleGetOperaList = () => {
  followUpListParams.value = {
    businessId: workItemForm.value.id,
    tableName: 'sys_requirement'
  }
}

//修改工时列表详情
const handleUpdateHoursInfo = item => {
  workingHoursForm.value = item
  workingHoursForm.value.typeName = '工作项'

  workingHoursDialog.value = true
  workingHoursForm.value.estimatedWorkHour =
    workItemForm.value.estimatedWorkHour
  workingHoursForm.value.itemName = workItemForm.value.title

  //   计算工时
  workingHoursFormChange('workHour')
}
//删除登记的工时记录
const handleDelHours = item => {
  let str = `确认删除${item.createTime}登记的${item.workHour}h工时吗？`
  ElMessageBox.confirm(str, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(({ value }) => {
      delWorkHour(item.id).then(res => {
        proxy.$modal.msgSuccess('删除成功')
        handleShowHoursList()
      })
    })
    .catch(() => {})
}

//值修改
const handleUpdateInfoProp = (val, row, prop) => {
  console.info('row', row)
  let params = {
    id: row.id,
    key: prop,
    value: val
  }

  updateBacklogProperty(params).then(res => {})
}

//显示工时列表
const handleShowHoursList = () => {
  hoursFormShow.value = false
  let params = {
    itemId: workItemForm.value.id,
    pageNum: 1,
    pageSize: 999
  }
  getWorkHourList(params).then(res => {
    console.info(res)
    hoursDataList.value = res.data
  })
}

//获取工作项信息
const handleGetWorkItemInfo = id => {
  getBacklogInfo(id).then(async res => {
    workItemForm.value = res.data
    formData.value.fileList = res.data.fileList
    if (res.data.directorId != null) {
      //获取部门人员数据
      const deptUserData = await commonStore.getUseTreeData({ deptId: '484' })
      console.info('deptUserData', deptUserData)
      //根据当前用户id获取uuid
      let obj = getTreeNodeByParam(deptUserData, res.data.directorId, 'id', [])
      console.info('obj', obj)
      selectOptionObj.value.directorId = obj
      workItemForm.value.directorId = obj[0].uuid
    }
  })
}

// 弹窗打开
const handleOpen = row => {
  visible.value = true
  activeName.value = 'basicInfo'
  proxy.$nextTick(() => {
    handleGetWorkItemInfo(row.id)
  })
}
//弹窗关闭
const handleClose = () => {
  visible.value = false
}

defineExpose({
  handleOpen
})

// 显示或者隐藏对象
const showHideObj = ref({
  directorId: false,
  status: false,
  startDate: false,
  endDate: false
})

// 工时确认
const handleWorkingHoursConfirm = () => {
  workingHoursFormRef.value.validate((valid, fields) => {
    if (valid) {
      saveWorkHours(workingHoursForm.value).then(res => {
        proxy.$modal.msgSuccess('添加成功')
        workingHoursDialog.value = false
        handleGetWorkItemInfo(workItemForm.value.id)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 工时弹窗关闭
const handleWorkingHoursDialogClose = () => {
  workingHoursDialog.value = false
}

//登记工时弹窗
const handleSetWorkingHours = () => {
  console.log('登记工时')
  workingHoursDialog.value = true

  workingHoursForm.value.workTime = ''
  workingHoursForm.value.workType = ''
  workingHoursForm.value.estimatedWorkHour =
    workItemForm.value.estimatedWorkHour
  workingHoursForm.value.surplusWorkHour = workItemForm.value.surplusWorkHour
  workingHoursForm.value.itemId = workItemForm.value.id
  workingHoursForm.value.itemName = workItemForm.value.title
  workingHoursForm.value.workHour = ''
  //   计算工时
  workingHoursFormChange('workHour')
}

// 工时表单选择
const workingHoursFormChange = type => {
  switch (type) {
    case 'workHour':
      console.log('登记工时')
      if (
        workingHoursForm.value.surplusWorkHour !== '' &&
        workingHoursForm.value.surplusWorkHour !== null &&
        workItemForm.value.workHour != null &&
        workItemForm.value.workHour != ''
      ) {
        console.info(123)
        //计算进度
        workingHoursForm.value.percentage =
          (
            (workItemForm.value.workHour -
              workingHoursForm.value.surplusWorkHour) /
            workItemForm.value.workHour
          ).toFixed(2) * 100
      } else {
        workingHoursForm.value.percentage = 0
      }

      break
    case 'surplusWorkHour':
      console.log('剩余工时')
      //计算进度
      if (
        workingHoursForm.value.surplusWorkHour !== '' &&
        workingHoursForm.value.surplusWorkHour !== null &&
        workItemForm.value.workHour != null &&
        workItemForm.value.workHour != ''
      ) {
        console.info(123)

        //计算进度
        workingHoursForm.value.percentage =
          (
            (workItemForm.value.workHour -
              workingHoursForm.value.surplusWorkHour) /
            workItemForm.value.workHour
          ).toFixed(2) * 100
      } else {
        workingHoursForm.value.percentage = 0
      }
      break
  }
  console.info(workingHoursForm.value)
}

//显示或者隐藏切换操作
const handleFormFocus = (key, refName) => {
  showHideObj.value[key] = true
  proxy.$nextTick(() => {
    proxy.$refs[refName].focus()
  })
}

// 标题修改显示
const handleInputNameShow = () => {
  inputNameShow.value = true
  proxy.$nextTick(() => {
    inputNameRef.value.focus()
  })
}

//form失去焦点事件
const handleFormBlur = type => {
  switch (type) {
    case 'directorId': //负责人
      showHideObj.value.directorId = false
      dialogParam.value.isDialog = false
      break
    case 'title': //标题
      inputNameShow.value = false
      handleUpdateInfoProp(
        workItemForm.value.title,
        workItemForm.value,
        'title'
      )
      break
    default:
      setTimeout(() => {
        showHideObj.value[type] = false
        handleUpdateInfoProp(workItemForm.value[type], workItemForm.value, type)
      }, 100)
    // case 'status': //状态
    //   setTimeout(() => {
    //     showHideObj.value.status = false
    //   }, 100)
    //
    //   break
    // case 'startDate': // 开始时间
    //   setTimeout(() => {
    //     showHideObj.value.startDate = false
    //   }, 100)
    //   break
    // case 'endDate': // 开始时间
    //   setTimeout(() => {
    //     showHideObj.value.endDate = false
    //   }, 100)
    //   break
  }
}

// 选择人员
const userInputFocus = () => {
  dialogParam.value.type = 'directorId'
  dialogParam.value.title = '选择负责人'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.apiParams = { deptId: userStore.user.orgId }

  dialogParam.value.defaultCheckedKeys = [workItemForm.value.directorId]
  dialogParam.value.dataType = 'person'
  dialogParam.value.isDialog = true
}

/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'directorId':
      selectOptionObj.value[val.type] = val.selectData
      workItemForm.value.director = val.selectData[0].label
      workItemForm.value.directorId = val.defaultCheckedKeys.toString()
      handleUpdateInfoProp(
        selectOptionObj.value[val.type][0].id,
        workItemForm.value,
        'directorId'
      )
      handleUpdateInfoProp(
        selectOptionObj.value[val.type][0].label,
        workItemForm.value,
        'director'
      )
      break
  }
}
</script>

<style scoped lang="scss">
.workItemInfo {
  :deep(.el-collapse-item__header) {
    background-color: #fafafacc;
  }

  :deep(.el-collapse-item__content) {
    background-color: #fafafacc;
  }

  :deep(.el-collapse-item__wrap) {
    background-color: #fafafacc;
  }

  :deep(.workItemInfoDialog .el-dialog__header) {
    display: none;
  }

  .info-title {
    @apply w-full cursor-text flex items-center py-3 pl-10px box-border;
    border: 1px solid transparent;

    .info-name {
      @apply text-3xl mr-10px;
      border: none;
    }
  }

  .info-title:hover {
    border: 1px solid #eee;
    box-sizing: border-box;
  }

  :deep(.el-form-item__label) {
    @apply pl-2;
  }

  :deep(.workItemInfoDialog .el-dialog__body) {
    min-height: 85vh;
    padding: 0;
  }

  .showHideClass {
    box-sizing: border-box;
    border: 1px solid #ffffff;
    @apply cursor-pointer flex items-center w-full pl-2 rounded-md;
    .formIcon {
      display: none;
    }
  }

  .showHideClass:hover {
    border: 1px solid #cccccc;

    .formIcon {
      display: block;
    }
  }

  .close {
  }
}

.riskColor1 {
  background: #f56c6c;
}

.riskColor2 {
  background: #e6a23c;
}

.riskColor3 {
  background: #909399;
}

.taskTypeIcon {
  display: inline-block;
  box-sizing: border-box;
  border-style: solid;
  background: transparent;
  width: 0;
  height: 0;
  border-width: 5px;
  border-radius: 2px;
}

.taskTypeColor1 {
  border-color: rgba(153, 215, 90, 0.6);
}

.taskTypeColor2 {
  border-color: rgba(45, 188, 255, 0.6);
}

.taskTypeColor3 {
  border-color: rgba(78, 138, 249, 0.6);
}

.taskTypeColor4 {
  border-color: rgba(148, 115, 253, 0.6);
}

.taskTypeColor5 {
  border-color: rgba(249, 105, 170, 0.6);
}

.taskTypeColor6 {
  border-color: rgba(255, 164, 21, 0.6);
}

.taskTypeColor7 {
  border-color: rgba(255, 117, 117, 0.6);
}
</style>
